package com.example.bledemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    public static BluetoothAdapter mBluetoothAdapter;
    public static BluetoothManager mBluetoothManager;
    public static BluetoothGatt    mBluetoothGatt;

    public static List<BluetoothDevice> mDeviceList=new ArrayList<>();
    private final List<Integer> mRssi=new ArrayList<>();
    private final List<byte[]> mScanRecord=new ArrayList<>();
    private ListView mListView;
    public static BleAdapter mBleAdapter;

    Button scanButton = null;

    String mac;

    private boolean isConnect = false;

    private TextView tv_discovery;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBluetoothManager=(BluetoothManager)getSystemService(BLUETOOTH_SERVICE);
        mBluetoothAdapter=mBluetoothManager.getAdapter();   //从系统服务中获取蓝牙适配器

        if(mBluetoothAdapter!=null){   //开启手机蓝牙
            if(!mBluetoothAdapter.isEnabled()){
                Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intent,1);
            }
        }
        mListView=findViewById(R.id.ble_list);
        mBleAdapter=new BleAdapter(mDeviceList, mRssi, mScanRecord, this);
        mListView.setAdapter(mBleAdapter);

        tv_discovery = (TextView) findViewById(R.id.tv_discovery);
        scanButton   = (Button)findViewById(R.id.scanButton);



        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Bundle bundle = new Bundle();

                bundle.putInt("position",arg2);

                mBluetoothAdapter.stopLeScan(leScanCallback);
                Intent intent = new Intent(MainActivity.this, BleDeviceWRActivity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        });

    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    public void onScanBluetooth(View view) {
        if(mBluetoothAdapter!=null&&mBluetoothAdapter.isEnabled()){ //蓝牙已开启的情况下
            String[] permissions={Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION};
            int checkSum=0;
            for(String permission:permissions){
                checkSum+=checkSelfPermission(permission);
            }
            if(checkSum!=0){
                requestPermissions(permissions,1);
            }

            mDeviceList.clear();
            mRssi.clear();
            mScanRecord.clear();
            mBleAdapter.notifyDataSetChanged();
            new Thread(new Runnable() {
                @Override
                public void run() {
//                    isScanning = true;

                    scanButton.post(new Runnable() {
                        @Override public void run() {
                            scanButton.setText("扫描中");
                            //还可以更新其他的控件
                        }
                    });
                    mBluetoothAdapter.startLeScan(leScanCallback);  //扫描设备
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    mBluetoothAdapter.stopLeScan(leScanCallback);
//                    isScanning = false;
                    scanButton.post(new Runnable() {
                        @Override public void run() {
                            scanButton.setText("扫描");
                            //还可以更新其他的控件
                        }
                    });
                }
            }).start();
        }
    }




    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private final BluetoothAdapter.LeScanCallback leScanCallback=new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            if(!mDeviceList.contains(device)){
                mRssi.add(rssi);
                mScanRecord.add(scanRecord);
                mDeviceList.add(device);

                Log.d("@@@@@@", device.getName() + device.getAddress() + " " + Integer.toString(rssi) + "\n" + Arrays.toString(scanRecord));
                mBleAdapter.notifyDataSetChanged();

            }
        }


    };


}

